#include "stm32f10x.h"

#include "iwdg.h"
#include "ds1302.h"
#include "usart1.h"
#include "delay.h"
#include "tftlcd.h"

int main()
{
    uint8_t High = 0, Low = 0, Data = 0;
    uint32_t DataTickStart = (uint32_t)-500000, TimeTickStart = (uint32_t)-1000000;

    // 看门狗时间 300 ms
    IWDG_Init(IWDG_Prescaler_16, 750);
    DS1302_Init();
    USART1_Init();
    Delay_Init();
    TFTLCD_Init();

    // 看门狗时间缩短至 70 ms
    IWDG_Init(IWDG_Prescaler_16, 175);
    LCD_ShowFontHZ(10, 10, "土壤湿度智能检测器");

    while (1)
    {
        IWDG_ReloadCounter();
        // 协议解析
        if (USART1_RxBuf.Head != USART1_RxBuf.End)
        {
            uint8_t New = USART1_RxBuf.Data[USART1_RxBuf.Head];
            uint8_t Sum = High + Low + New + 1;
            // 校验成功
            if (Sum == 0)
            {
                uint16_t TmpData = (High << 8) | Low;
                High = 0;
                Low = 0;
                if (TmpData > 4000)
                {
                    Data = 0;
                }
                else if (TmpData < 2000)
                {
                    Data = 100;
                }
                // 2000 <= TmpData <= 4000
                else
                {
                    Data = 100 - ((TmpData - 2000) / 20);
                }
            }
            else
            {
                High = Low;
                Low = New;
            }
            USART1_RxBuf.Head = (USART1_RxBuf.Head + 1) % USART_BUFFER_SIZE;
        }
        // 显示湿度数据
        if (Get_Tick() - DataTickStart > 500000)
        {
            DataTickStart = Get_Tick();
            LCD_ShowNum(10, 50, Data, 3, 24);
            LCD_ShowChar(46, 50, '%', 24, 0);
        }
        // 显示日期和时间
        if (Get_Tick() - TimeTickStart > 1000000)
        {
            TimeTickStart = Get_Tick();
            // 一个尺寸为 24 的西文字符实际大小为 12 * 24
            LCD_ShowNum(10, 80, 2000 + DS1302_Get_Year(), 4, 24);
            LCD_ShowChar(10 + 12 * 4, 80, '-', 24, 0);
            LCD_ShowxNum(10 + 12 * 5, 80, DS1302_Get_Mouth(), 2, 24, 1 << 7);
            LCD_ShowChar(10 + 12 * 7, 80, '-', 24, 0);
            LCD_ShowxNum(10 + 12 * 8, 80, DS1302_Get_Date(), 2, 24, 1 << 7);
            // 时间和日期间隔一格
            LCD_ShowNum(10 + 12 * 11, 80, DS1302_Get_Hour(), 2, 24);
            LCD_ShowChar(10 + 12 * 13, 80, ':', 24, 0);
            LCD_ShowxNum(10 + 12 * 14, 80, DS1302_Get_Min(), 2, 24, 1 << 7);
            LCD_ShowChar(10 + 12 * 16, 80, ':', 24, 0);
            LCD_ShowxNum(10 + 12 * 17, 80, DS1302_Get_Sec(), 2, 24, 1 << 7);
        }
    }
}
